<?php
/**
 * This is the administration_controller class file.
 * @author Arsene Tochemey GANDOTE<arsene.gandote@yahoo.com>
 *                    Amissah Gideon<kuulmek@yahoo.com>
 * @access public
 * @version 1.0
 * @copyright (c) 2011. Coco Software Foundation
 */

class AdministrationController extends AppController {
    # Controller Name to be used
       var $name = 'Administration';

      # Models to be used
       var $uses = array(
           'User',
           'Organisation',
           'Module',
           'Configuration',
           'PropertyGroup',
           'Location',
           'PropertyGroupType',
           'PropertyGroupSubType'	  	   
       );


       # set the layout to use
       var $layout = 'administration_layout';
       
       # set the name of this module
       var $moduleName = 'Administration';

       # Check the authenticity of the user
       function  beforeFilter() {
              parent::setUpGlobalConfig();  
              # Check the user validity
              if($this->Session->check('userSessionData')){
                     $loggedUser =  $this->Session->read('userSessionData');
                     $userData = $this->User->getUserById($loggedUser['id']);
                     $userModules = $userData['Module'];
                     $allowed = false;
                     foreach($userModules as $module){
                        if($module['name'] === $this->moduleName){
                            $allowed = true;
                        }
                     }
                     if(!$allowed){
                          $this->redirect(array('controller' => 'Dashboard', 'action' => 'index'));
                     }
              }
              else{
                      $this->redirect('/');
              }
       }
       
       # Controller actions
       /**
        * This function displays all the users in the system
        * @name index
        * @param void
        * @return Array of data.
        * @access public
        */
       function index(){
        
            $prpGroup = Hash::combine($this->PropertyGroup->find('all',array('conditions' => array('deleted'=>0),'fields'=>array('id','group_name'),'recursive'=>-1)),'{n}.PropertyGroup.id', '{n}.PropertyGroup');
            $jsonArr = array(array('name'=>'All','value'=>0));
            foreach($prpGroup as $key => $value){
                $jsonArr[] = array('name'=>$value['group_name'],'value'=>$value['id']);
            }
            
            $prpFieldGroup = $this->PropertyGroup->find('all',array(
                    'fields'=>array('id','group_name','fields'),
                    'conditions' => array('deleted'=>0),
                    'contain'=>array(
                        'PropertyGroupType'=>array(
                            'fields'=>array('id','type_name'),
                            'conditions' => array('deleted'=>0),
                            'PropertyGroupSubType'=>array(
                                'fields'=>array('id','sub_type_name'),
                                'conditions' => array('deleted'=>0)
                            )
                        ),
                    ),
                    'recursive'=>2
                )
            );
            //debug($prpFieldGroup);
            $prpGroupData = array();
            foreach($prpFieldGroup as $value){
                $prpGroupData[$value['PropertyGroup']['id']]['id'] = $value['PropertyGroup']['id'];
                $prpGroupData[$value['PropertyGroup']['id']]['group_name'] = $value['PropertyGroup']['group_name'];
                
                if($value['PropertyGroup']['fields']){
                    $fields_arr = explode(',',$value['PropertyGroup']['fields']);
                    foreach($fields_arr as $value_0){
                        $prpGroupData[$value['PropertyGroup']['id']]['fields'][] = $value_0;
                    }
                }
                else{
                    $prpGroupData[$value['PropertyGroup']['id']]['fields'] = array();
                }
                
                foreach($value['PropertyGroupType'] as $value_1){
                    $prpGroupData[$value['PropertyGroup']['id']]['group_type'][$value_1['id']]['id'] = $value_1['id'];
                    $prpGroupData[$value['PropertyGroup']['id']]['group_type'][$value_1['id']]['type_name'] = $value_1['type_name'];
                    
                    foreach($value_1['PropertyGroupSubType'] as $value_2){
                        $prpGroupData[$value['PropertyGroup']['id']]['group_type'][$value_1['id']]['group_sub_type'][$value_2['id']]['id'] = $value_2['id'];
                        $prpGroupData[$value['PropertyGroup']['id']]['group_type'][$value_1['id']]['group_sub_type'][$value_2['id']]['sub_type_name'] = $value_2['sub_type_name'];
                    }
                }
                
            }
        
            $loc_data = Hash::combine($this->Location->find('all',array(
                    'fields'=>array('id','location_name','location_code'),
                    'conditions' => array('deleted'=>0),
                    'recursive'=>-1
                )
            ),'{n}.Location.id', '{n}.Location');
            
            $grouptype_data = Hash::combine($this->PropertyGroupType->find('all',array(
                    'fields'=>array('id','type_name','property_group_id'),
                    'conditions' => array('deleted'=>0),
                    'recursive'=>-1
                )
            ),'{n}.PropertyGroupType.id', '{n}.PropertyGroupType');
            
            $group_subtype_data = Hash::combine($this->PropertyGroupSubType->find('all',array(
                    'fields'=>array('id','sub_type_name','property_group_type_id'),
                    'conditions' => array('deleted'=>0),
                    'recursive'=>-1
                )
            ),'{n}.PropertyGroupSubType.id', '{n}.PropertyGroupSubType');


            
            $this->set(compact('jsonArr','prpGroupData','loc_data','grouptype_data','group_subtype_data'));  
       }
       
        # Dashboard actions
       /**
        * This function displays all the admin menus
        * @name dashboard
        * @param void
        * @access public
        */
       function dashboard(){
         $this->layout = "dashboard_layout";
       }

       /**
        * This function add a new record to the database
        * @name add
        * @param void
        * @return Json data
        * @access public
        */
       function add(){
              # Get the user session data
              $loggedUser =  $this->Session->read('userSessionData');
              # check whether the HTTP Request is an ajax request
              if($this->request->is('ajax')){
                     # disable the rendering of the layout
                     $this->autoRender = false;
                     $this->autoLayout = false;
                     # retrieve the model
                     $model = ucfirst($_POST['model']);
                     # Check the model
                     switch($model){
                          case 'User' :
                              
                        	$upt_id = ($_POST['row_id'] != 'null') ? $_POST['row_id'] : false;
                        	$loggedUser =  $this->Session->read('userSessionData');
                        	$loggedUser_id = $loggedUser['id'];
                        	$save_date = date('Y-m-d H:i:s');
                        	
                        	if($upt_id){ /** Edit User*/
                        		$this->User->id = $upt_id; 	
                        		//$userObj = new User($upt_id);
                        		$this->request->data['User']['modified_by'] =	$loggedUser_id;
                        		$this->request->data['User']['modification_date'] =	$save_date;
                        		/** Delete All users modules and insert new ones*/
                        		$this->User->ModulesUser->deleteAll(array('ModulesUser.user_id' => $upt_id), false);
                        	}
                        	else{ /** New User*/
                        		$this->User->create();
                        		$this->request->data['User']['created_by'] =	$loggedUser_id;
                        		$this->request->data['User']['creation_date'] =	$save_date;
                        		
                        	   // $userObj = new User();
                        	}
                        	
                        	$this->User->bindModel(array('hasMany'=>array('ModulesUser')));
                        	$this->request->data['User']['password'] = md5($this->request->data['User']['password']);
                        	
                        	# save the data
                        	if($upt_id){ 
                        		if($this->User->save($this->request->data['User'])){
                        		     //  debug($this->request->data['ModulesUser']);
                        			 $mod_arr = array();
                                     foreach($this->request->data['ModulesUser'] as $row){
                                        $mod_arr[] = array(
                                            'module_id' => $row['module_id'],
                                            'user_id' => $upt_id
                                        );
                                     }
                                     $this->request->data['ModulesUser'] = $mod_arr;
                                     //debug($this->request->data['ModulesUser']);

                        	        $res = $this->User->ModulesUser->saveAll($this->request->data['ModulesUser']);
                                    if($res){
                                        return json_encode(array('code' => 0, 'mesg' => 'Data Saved'));
                                    }
                                    else{
                                        return json_encode(array('code' => 1, 'mesg' => $res));
                                    }   
                            	}
                        		else{
                        			  return json_encode(array('code' => 1, 'mesg' => $userObj->invalidFields()));
                        		}  
                        	}
                        	else{
                        		if($this->User->saveAll($this->request->data)){
                           			  return json_encode(array('code' => 0, 'mesg' => 'Data Saved'));
                        		}
                        		else{
                        			  return json_encode(array('code' => 1, 'mesg' => $this->User->invalidFields()));
                        		}    
                        	}
                           
                           break;
                                   
                            case 'Organisation':
                            
                                  // $this->Organisation->id = $this->request->data['Organisation'];
                                  /* Update the data  */                                   
                                    if(!empty($this->request->data)) {
                                        
                                         if($this->Organisation->save($this->request->data)){
                                            return json_encode(array('code' => 0, 'data' =>$this->request->data['Organisation'], 'mesg' => 'Data successfully recorded. You need to reload the page for the new changes to be applied'));
                                         }
                                         else{
                                            return json_encode(array('code' => 1, 'data' =>$this->request->data['Organisation'], 'mesg' => 'Data not successfully recorded'));
                                         }
                                    } 

                            break;
                                   
                            case 'Modules':
                                     
                                    /* Update the data */                                     
                                    if(!empty($this->request->data)) {
                                        
                                         if($this->Module->saveAll($this->request->data['Module'])){
                                                return json_encode(array('code' => 0, 'mesg' => 'Modules Configuration Saved!'));
                                         }
                                         else{
                                                 return json_encode(array('code' => 1, 'mesg' => 'Modules Configuration not Saved'));
                                         }
                                    } 
                                   
                            break;
                                   
                            case 'SystemConfig':
                                    /* Update the data */                                     
                                    if(!empty($this->request->data)) {
                                        
                                         if($this->Configuration->saveAll($this->request->data['Configuration'])){
                                                return json_encode(array('code' => 0, 'mesg' => 'System Configuration Saved!'));
                                         }
                                         else{
                                                return json_encode(array('code' => 1, 'mesg' => 'System Configuration not Saved'));
                                         }
                                    }                                   
                            break;
                            
                            case 'Location':
                                   $type = isset($_POST['type']) ? $_POST['type'] : '';
                                    if($type == 'add'){
                                        $this->Location->create();   
                                    }
                                    else if($type == 'edit'){
                                        $upt_id = $_POST['id'];
                                        $this->Location->id = $upt_id;
                                    }
                                                                     
                                    if(!empty($this->request->data)) {
                                        
                                         if($this->Location->save($this->request->data)){
                                                $save_id = $this->Location->id;
                                                return json_encode(array('code' => 0, 'id'=>$save_id,'mesg' => 'Data Saved!'));
                                         }
                                         else{
                                                return json_encode(array('code' => 1, 'mesg' => 'Data not Saved'));
                                         }
                                    }                                   
                            break;
                            
                            case 'GroupType':
                                   $type = isset($_POST['type']) ? $_POST['type'] : '';
                                    if($type == 'add'){
                                        $this->PropertyGroupType->create();   
                                    }
                                    else if($type == 'edit'){
                                        $upt_id = $_POST['id'];
                                        $this->PropertyGroupType->id = $upt_id;
                                    }
                                                                     
                                    if(!empty($this->request->data)) {
                                        
                                         if($this->PropertyGroupType->save($this->request->data)){
                                                $save_id = $this->PropertyGroupType->id;
                                                return json_encode(array('code' => 0, 'id'=>$save_id, 'group_id'=>$this->request->data['PropertyGroupType']['property_group_id'],'mesg' => 'Data Saved!'));
                                         }
                                         else{
                                                return json_encode(array('code' => 1, 'mesg' => 'Data not Saved'));
                                         }
                                    }                                   
                            break;
                            
                            case 'GroupSubType':
                                   $type = isset($_POST['type']) ? $_POST['type'] : '';
                                    if($type == 'add'){
                                        $this->PropertyGroupSubType->create();   
                                    }
                                    else if($type == 'edit'){
                                        $upt_id = $_POST['id'];
                                        $this->PropertyGroupSubType->id = $upt_id;
                                    }
                                                                     
                                    if(!empty($this->request->data)) {
                                        
                                         if($this->PropertyGroupSubType->save($this->request->data)){
                                                $save_id = $this->PropertyGroupSubType->id;
                                                return json_encode(array('code' => 0, 'id'=>$save_id, 'group_type_id'=>$this->request->data['PropertyGroupSubType']['property_group_type_id'],'mesg' => 'Data Saved!'));
                                         }
                                         else{
                                                return json_encode(array('code' => 1, 'mesg' => 'Data not Saved'));
                                         }
                                    }                                   
                            break;

                     }
              }
       }
       
       function updateGroupField($typeP, $fieldP, $group_idP){
            $this->autoRender = false;
            $this->autoLayout = false;
            if($this->request->is('ajax')){
                $type = $_POST['type']; 
                $field = $_POST['field']; 
                $group_id = $_POST['group_id'];
            }
            else{
                $type = $typeP; 
                $field = $fieldP; 
                $group_id = $group_idP;
            }
            
            $prpGroup = $this->PropertyGroup->find('first',array(
                'conditions' => array('id'=>$group_id),
                'fields'=>array('id','group_name'),'recursive'=>-1)
            );
            
            debug($prpGroup);
            
            return;
            
       }
       
       
        /**
        * This function load the add user form
        * @param void
        * @return html
        * @access public
        */
       function loadUser(){
            $this->autoRender = false;
            $this->autoLayout = false;
            
            /** Loading */
            $userData = $this->User->getUserById($_POST['user-id']);
            
            $model_arr = array();
            if($userData['Module']){
                foreach($userData['Module'] as $row){
                   $model_arr[] = $row['id'];
                }
                
                $userData['Module'] = $model_arr;
            }
            
            if($userData){                
                return json_encode(array('code' => 0, 'data' => $userData, 'mesg' => 'Data Found'));
            }
            else{
                return json_encode(array('code' => 1, 'data' => array(), 'mesg' => 'No Record Found'));
            }
       }

       
       
        #Delete Users via ajax
	    function deleteUsers(){
            $loggedUser =  $this->Session->read('userSessionData');
			if($this->request->is('ajax')){
				$this->autoRender = false;
				$this->autoLayout = false;
                 
                $ids = $_POST['ids'];
                $user = ClassRegistry::init('User');
                $result = $user->updateAll(
					array('User.deleted' => 1 ), 
					array('User.id' => $ids)
				);
				
				if($result){
					 echo json_encode(array('code' => 0, 'mesg' => 'Selected Users have been successfully deleted'));
				}
				else{
					echo json_encode(array('code' => 1, 'mesg' => 'Selected Users cannot be deleted'));
				}
             }
		}
       

       /**
        * @name getUsers
        * @param void
        * @return Json Data
        */
         function getUsers(){
            # disable the rendering of the layout
            $this->autoRender = false;
            $this->autoLayout = false;
            
            /**  Get posted data */
            $page =      isset($_POST['page']) ? $_POST['page'] : 1 ; /** The current page */
            $sortname =  isset($_POST['sortname']) ? $_POST['sortname'] : 'id' ; /** Sort column */
            $sortorder = isset($_POST['sortorder']) ? $_POST['sortorder'] : 'desc' ; /** Sort order */
            $qtype =     isset($_POST['qtype']) ? $_POST['qtype'] : '' ; /** Search column */
            $search_query =     isset($_POST['query']) ? $_POST['query'] : '' ; /** Search string */
            $rp =        isset($_POST['rp']) ? $_POST['rp'] : 10 ;
            $limit = $rp;
            $start = ($page-1) * $rp;
            
            $condition_array = array('User.deleted' => 0);
            if (!empty($search_query)){
                if($search_query == 'username'){
                    $condition_array = array(
                       'User.username' => $search_query,
                       'User.deleted' => 0
                     );
                }
                else{
                    $condition_array = array(
                       "User.$qtype LIKE" => $search_query . '%',
                       'User.deleted' => 0
                     );
                }
            }
            
            $fields = array('User.id','User.username','User.first_name','User.last_name','User.creation_date','User.status');
            $users = $this->User->find('all', array('fields'=>$fields,'conditions' => $condition_array,'order' => "User.$sortname $sortorder",'limit'=>$limit,
            'offset'=>$start,'recursive' => -1));
            $usersCount  = $this->User->find('count', array('conditions' => $condition_array,'recursive' => -1));
            
            $total_records = $usersCount;

            if($users){
                $return_arr = array();
                foreach ($users as $obj){
                   
                   $status = (intval($obj['User']['status']) == 1) ? 'Active' : 'Inactive';
                    
                   $return_arr[] = array(
                        'id' => $obj['User']['id'],
                        'cell' => array(
                            $obj['User']['id'], 
                            $obj['User']['username'], 
                            $obj['User']['first_name'], 
                            $obj['User']['last_name'], 
                            $obj['User']['creation_date'], 
                            $status
                        )
                   );                  
                }
                return json_encode(array('success' => true, 'total'=>$total_records, 'page' => $page,'rows' => $return_arr));
            }
            else{
               return json_encode(array('success' => false, 'total'=>$total_records, 'page' => $page, 'rows' => array()));
            }       		
             
        }
        
        /** Delete Locations**/
	    function deleteLocation(){
            $loggedUser =  $this->Session->read('userSessionData');
			if($this->request->is('ajax')){
				$this->autoRender = false;
				$this->autoLayout = false;
                 
                $id = $_POST['id'];
                $obj = ClassRegistry::init('Location');
                $result = $obj->updateAll(
					array('Location.deleted' => 1 ), 
					array('Location.id' => $id)
				);
				
				if($result){
					 echo json_encode(array('code' => 0, 'mesg' => 'Data successfully deleted'));
				}
				else{
					echo json_encode(array('code' => 1, 'mesg' => 'Data cannot be deleted'));
				}
             }
		}
        
        
         /** Delete PropertyGroupType**/
	    function deletePropertyGroupType(){
            $loggedUser =  $this->Session->read('userSessionData');
			if($this->request->is('ajax')){
				$this->autoRender = false;
				$this->autoLayout = false;
                 
                $id = $_POST['id'];
                /** $obj = ClassRegistry::init('PropertyGroupType');
                $result = $obj->updateAll(
					array('PropertyGroupType.deleted' => 1 ), 
					array('PropertyGroupType.id' => $id)
				);*/
                
                $query = "UPDATE property_group_types SET deleted = 1  WHERE id = $id ";
                $result = $this->PropertyGroupType->query($query);
				
				if($result){
					 echo json_encode(array('code' => 0, 'mesg' =>'Data successfully deleted'));
				}
				else{
					echo json_encode(array('code' => 1, 'mesg' => 'Data cannot be deleted'));
				}
             }
		}
        
        
         /** Delete PropertyGroupSubType**/
	    function deletePropertyGroupSubType(){
            $loggedUser =  $this->Session->read('userSessionData');
			if($this->request->is('ajax')){
				$this->autoRender = false;
				$this->autoLayout = false;
                 
                $id = $_POST['id'];
               /** $obj = ClassRegistry::init('PropertyGroupSubType');
                $result = $obj->updateAll(
					array('PropertyGroupSubType.deleted' => 1 ), 
					array('PropertyGroupSubType.id' => $id)
				);*/
				
                $query = "UPDATE property_group_sub_types SET deleted = 1  WHERE id = $id ";
                $result = $this->PropertyGroupSubType->query($query);
                
				if($result){
					 echo json_encode(array('code' => 0, 'mesg' => 'Data successfully deleted'));
				}
				else{
					echo json_encode(array('code' => 1, 'mesg' => 'Data cannot be deleted'));
				}
             }
		}
       
       
        
        
        /**
        * This function upload file
        * @name uploadFile
        * @param void
        * @return html data
        * @access public
        */
       function uploadFile(){
              $this->autoRender = false;
               $this->autoLayout = false;
              $this->uses = array(
                      'Organisation'
              );              
              # Get the user session data
              $loggedUser =  $this->Session->read('userSessionData');
              
              $this->Organisation->id = $_POST['org-id'];
              # folder path structure
              $folder = 'img/uploaded_files/';
              $folder_db = 'uploaded_files/';

              # setup directory pathname
              $folderAbsPath = WWW_ROOT.$folder;
              $folderRelPath = $folder;

              # create folders if it does not exist
              if(!is_dir($folderAbsPath)){
                     mkdir($folderAbsPath, 0777, true);
              }

              # get the file details
              $rawFile = $folderAbsPath.basename($_FILES['uploadfile']['name']);
              $rawFile_rel = $folder_db.basename($_FILES['uploadfile']['name']);

              // replace spaces with underscores
              $fileName = str_replace(' ', '_', $rawFile);
              $fileName_rel = str_replace(' ', '_', $rawFile_rel);

              $fileType = $_FILES['uploadfile']['type'];

              # list of permitted file types, this is only images but documents can be added
              $permitted = array('image/gif','image/jpeg','image/pjpeg','image/png');

              $typeOk = false; # with the correct type the file will be uploaded or rejected.

              foreach($permitted as $type){
                     if($type == $fileType){
                            $typeOk = true;
                            break;
                     }
              }
              # if typeOk upload the file
              if($typeOk){
                     # check whether the file already exists or not
                     if(!file_exists($fileName)){
                            # upload the file
                            if (move_uploaded_file($_FILES['uploadfile']['tmp_name'], $fileName)) {
                                   # update the file details in the database
                                   $this->request->data['Organisation'] = array(
                                       'logo_path' =>$fileName_rel,
                                       'modified_by' => $loggedUser['id'],
                                       'modification_date' =>date('Y-m-d H:i:s')
                                   );

                                   if($this->Organisation->save($this->request->data, false) == true){
                                          echo 0;
                                   }
                                   else if($this->Organisation->save($this->request->data, false) == false){
                                          echo 1;
                                   }
                            }
                            else {
                                     echo 1;
                            }
                     }
                     else{
                            echo 2;
                     }
              }
              else{
                     echo 3;
              }
       }

}
?>
